package com.zjx.shop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjx.shop.common.utils.PageParams;
import com.zjx.shop.product.entity.VO.Catalog2VO;
import com.zjx.shop.product.service.CategoryBrandRelationService;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjx.shop.common.utils.PageUtils;
import com.zjx.shop.product.dao.CategoryDao;
import com.zjx.shop.product.entity.CategoryEntity;
import com.zjx.shop.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu)->{
                    // 设置一级分类的子分类
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                }).sorted((menu1, menu2) -> {
                    //排序
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());


        return level1Menus;
    }

    @Override
    public PageUtils queryPage(PageParams params) {
        IPage<CategoryEntity> page = this.page(
                new Page<>(params.getPage(),params.getSize()),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page.getCurrent(),page.getSize(),(long) page.getRecords().size(),page.getRecords());
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream()
                .filter(CategoryEntity -> CategoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    //递归查找
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return children;
    }

    //查找完整路径方法
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    //递归查找父节点id
    public List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(), paths);
        }
        paths.add(catelogId);
        return paths;
    }

    /**
     * 失效模式： 更新时 顺便把category的缓存删掉
     * @param category
     */
    @CacheEvict(value = {"category"},allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 查出所有1级分类
     */
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public Map<String, List<Catalog2VO>> getLevel2Categorys(){
        //优化业务逻辑，仅查询一次数据库
        List<CategoryEntity> categoryEntities = this.list();
        //查出所有一级分类
        List<CategoryEntity> level1Categories = getCategoryByParentCid(categoryEntities, 0L);
        Map<String, List<Catalog2VO>> listMap = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //遍历查找出二级分类
            List<CategoryEntity> level2Categories = getCategoryByParentCid(categoryEntities, v.getCatId());
            List<Catalog2VO> catalog2Vos = null;
            if (level2Categories != null) {
                //封装二级分类到vo并且查出其中的三级分类
                catalog2Vos = level2Categories.stream().map(cat -> {
                    //遍历查出三级分类并封装
                    List<CategoryEntity> level3Catagories = getCategoryByParentCid(categoryEntities, cat.getCatId());
                    List<Catalog2VO.Catalog3Vo> catalog3Vos = null;
                    if (level3Catagories != null) {
                        catalog3Vos = level3Catagories.stream()
                                .map(level3 -> new Catalog2VO.Catalog3Vo(level3.getParentCid().toString(), level3.getCatId().toString(), level3.getName()))
                                .collect(Collectors.toList());
                    }
                    Catalog2VO catalog2Vo = new Catalog2VO(v.getCatId().toString(), catalog3Vos , cat.getCatId().toString(), cat.getName());
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return listMap;
    }









    /**
     * TODO 缓存问题
     * 空结果缓存：解决缓存穿透（查询null的数据）  \spring-cache:cache-null-values: true
     * 设置过期时间加随机值/过期时间不同：解决缓存雪崩（大量key同时失效）  \spring-cache:
     * 加锁；解决缓存击穿（高并发同一个key，key刚还失效）  \spring-cache: time-to-live: 3600000
     * @return
     */
    public Map<String, List<Catalog2VO>> getCatalog2VO(){
        String value = stringRedisTemplate.opsForValue().get("catlogJson");
        if (StringUtils.isEmpty(value)){
            Map<String, List<Catalog2VO>> res = getCatalogJson1();
            return res;
        }
        Map<String, List<Catalog2VO>> res = JSON.parseObject(value,new TypeReference<Map<String, List<Catalog2VO>>>(){});
        return res;
    }

    /**
     * TODO 本地锁
     * 加锁（本地锁） ： 解决缓存击穿
     * 先竞争，竞争到的查数据库，查完存入redis并返回，下一个进来的查看是否有缓存，有缓存直接返回缓存
     * @return
     */
    public Map<String, List<Catalog2VO>> getCatalogJson1() {

        synchronized (this){
            return getFromDb();
        }
    }

    /**
     * TODO 分布式锁 简易自制版
     * 分布式锁 ： 在 redis 加锁 set + NS 命令 ，第一个set ，后面的 set 不了
     * 阶段一： 未删除直接死机，死锁；解决：给锁加过期时间
     * 阶段二： 锁的过期时间设置代码没有执行就死机； 解决：原子加锁与过期时间
     * 阶段三： 锁的过期时间短语业务代码的执行时间，执行完后锁已经自动删除，再执行一次删锁，误删别人的锁； 解决：校验是否自己的锁
     * 阶段四： 校验时是自己的锁，校验后自己的锁解除，误删别人的锁； 解决：原子校验与删锁，lua脚本
     * 阶段五： 业务时间过长，锁过期； 解决：锁自动续期\设置长时间
     */
    public Map<String, List<Catalog2VO>> getCatalogJson2() {

        String uuid = UUID.randomUUID().toString();
        //占分布式锁
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock","1",300,TimeUnit.SECONDS);
        if (lock){
            //占锁成功
            Map<String, List<Catalog2VO>> res;
            try{
                res = getFromDb();
            }finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class)
                        ,Arrays.asList("lock"),uuid);
            }
            return res;
        }else {
            //占锁失败
            try {
                Thread.sleep(200);
            }catch (Exception e){

            }
            return getCatalogJson2();
        }
    }

    /**
     * TODO 分布式锁框架redisson
     * 1.获取锁
     *  RLock lock = redissonClient.getLock("redisson_lock");
     * 2.加锁
     * lock.lock();
     * lock.lock(10, TimeUnit.SECONDS);
     * 3.解锁
     * lock.unlock();
     * 优点：
     *  1）锁自动续期+30S，业务超长情况下（看门狗）
     *  2）如果线程宕机，看门狗不会自动续期，锁会自动过期
     *  3）unlock使用lua脚本释放锁，不会出现误删锁
     *
     * 读写锁
     *  RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
     *  RLock rLock = readWriteLock.readLock();
     *  rLock.lock();
     *  rLock.unlock();
     *
     *  RLock rLock1 = readWriteLock.writeLock();
     *  rLock1.lock();
     *  rLock1.unlock();
     *
     *  闭锁（关门）
     *  RCountDownLatch door = redissonClient.getCountDownLatch("door");
     *  door.trySetCount(5);//全部人走完才能关门，否则等待
     *  door.await();
     *
     *  RCountDownLatch door = redissonClient.getCountDownLatch("door");
     *  door.countDown();//走一个人
     *
     *  信号量(停车位)
     *  RSemaphore park = redissonClient.getSemaphore("park");
     *  park.acquire();//停车，有车位才能停车，否则等待
     *
     *  RSemaphore park = redissonClient.getSemaphore("park");
     *  park.release();//释放一个车位
     *
     *  缓存数据一致性
     *  双写模式: 级联更新
     *  失效模式：更新完数据库，删除对应缓存
     *  都存在脏数据问题，需要加锁（读写），但是加锁会笨重，所以经常需要更新的数据不适合用缓存，用数据库更好
     * @return
     */
    public Map<String, List<Catalog2VO>> getCatalogJson3() {

        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();

        Map<String, List<Catalog2VO>> res;
        try{
            res = getFromDb();
        }finally {
            lock.unlock();
        }
        return res;

    }


    public Map<String, List<Catalog2VO>> getFromDb(){

        String value = stringRedisTemplate.opsForValue().get("catlogJson");
        //已经有人进来
        if (!StringUtils.isEmpty(value)){
            return JSON.parseObject(value,new TypeReference<Map<String, List<Catalog2VO>>>(){});
        }
        //优化业务逻辑，仅查询一次数据库
        List<CategoryEntity> categoryEntities = this.list();
        //查出所有一级分类
        List<CategoryEntity> level1Categories = getCategoryByParentCid(categoryEntities, 0L);
        Map<String, List<Catalog2VO>> listMap = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //遍历查找出二级分类
            List<CategoryEntity> level2Categories = getCategoryByParentCid(categoryEntities, v.getCatId());
            List<Catalog2VO> catalog2Vos = null;
            if (level2Categories != null) {
                //封装二级分类到vo并且查出其中的三级分类
                catalog2Vos = level2Categories.stream().map(cat -> {
                    //遍历查出三级分类并封装
                    List<CategoryEntity> level3Catagories = getCategoryByParentCid(categoryEntities, cat.getCatId());
                    List<Catalog2VO.Catalog3Vo> catalog3Vos = null;
                    if (level3Catagories != null) {
                        catalog3Vos = level3Catagories.stream()
                                .map(level3 -> new Catalog2VO.Catalog3Vo(level3.getParentCid().toString(), level3.getCatId().toString(), level3.getName()))
                                .collect(Collectors.toList());
                    }
                    Catalog2VO catalog2Vo = new Catalog2VO(v.getCatId().toString(), catalog3Vos , cat.getCatId().toString(), cat.getName());
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        stringRedisTemplate.opsForValue().set("catlogJson",JSON.toJSONString(listMap),1, TimeUnit.DAYS);

        return listMap;
    }

    private List<CategoryEntity> getCategoryByParentCid(List<CategoryEntity> categoryEntities, long l) {
        List<CategoryEntity> res = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == l).collect(Collectors.toList());
        return res;
    }


}